﻿@using Xms.Schema.Extensions;
@model Xms.Web.Customize.Models.EditAttributeModel

<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">
            <a data-toggle="collapse"
               href="#collapseTwo">
                <strong>@app.PrivilegeTree?.LastOrDefault().DisplayName</strong>
            </a>
        </h3>
    </div>
    <div id="collapseTwo" class="panel-collapse collapse in">
        <div class="panel-body">
            <form action="/@app.OrganizationUniqueName/customize/attribute/editattribute" method="post" id="editform" class="form-horizontal" role="form">
                @Html.AntiForgeryToken()
                @Html.ValidationSummary()
                @Html.HiddenFor(x => x.AttributeId)
                @Html.HiddenFor(x => x.EntityId)
                @Html.HiddenFor(x => x.SolutionId)
                @Html.HiddenFor(x => x.SummaryExpression)
                @Html.HiddenFor(x => x.FormulaExpression)
                <input type="hidden" id="filterConditions" value="" />
                <input type="hidden" id="valueSetJson" value="" />
                <div class="form-group col-sm-12">
                    @Html.LabelFor(x => x.Name, app.T["attribute_name"], new { @class = "col-sm-2 control-label" })
                    <h4 class="col-sm-10 control-text">
                        <span class="label label-info">@Model.Name</span>
                    </h4>
                </div>
                <div class="form-group col-sm-12">
                    @Html.LabelFor(x => x.LocalizedName, app.T["attribute_displayname"], new { @class = "col-sm-2 control-label" })
                    <div class="col-sm-10">
                        @Html.TextBoxFor(x => x.LocalizedName, new { @class = "form-control required" })
                    </div>
                </div>
                <div class="form-group col-sm-12">
                    @Html.LabelFor(x => x.IsRequired, app.T["required"], new { @class = "col-sm-2 control-label" })
                    <div class="col-sm-10">
                        <label class="checkbox-inline">
                            @Html.RadioButtonFor(x => x.IsRequired, true, new { @class = "required" }) @app.T["yes"]
                        </label>
                        <label class="checkbox-inline">
                            @Html.RadioButtonFor(x => x.IsRequired, false, new { @class = "required" }) @app.T["no"]
                        </label>
                    </div>
                </div>
                <div class="form-group col-sm-12">
                    @Html.LabelFor(x => x.LogEnabled, app.T["attribute_isloged"], new { @class = "col-sm-2 control-label" })
                    <div class="col-sm-10">
                        <label class="checkbox-inline">
                            @Html.RadioButtonFor(x => x.LogEnabled, true, new { @class = "required" }) @app.T["enabled"]
                        </label>
                        <label class="checkbox-inline">
                            @Html.RadioButtonFor(x => x.LogEnabled, false, new { @class = "required" }) @app.T["disabled"]
                        </label>
                    </div>
                </div>
                <div class="form-group col-sm-12">
                    @Html.LabelFor(x => x.AuthorizationEnabled, app.T["attribute_issecured"], new { @class = "col-sm-2 control-label" })
                    <div class="col-sm-10">
                        <label class="checkbox-inline">
                            @if (Model.IsPrimaryField)
                            {
                                @Html.RadioButtonFor(x => x.AuthorizationEnabled, true, new { @class = "required", @disabled = "disabled" })
                            }
                            else
                            {
                                @Html.RadioButtonFor(x => x.AuthorizationEnabled, true, new { @class = "required" })
                            }
                            @app.T["enabled"]
                        </label>
                        <label class="checkbox-inline">
                            @if (Model.Name.IsCaseInsensitiveEqual("name"))
                            {
                                @Html.RadioButtonFor(x => x.AuthorizationEnabled, false, new { @class = "required", @disabled = "disabled" })
                            }
                            else
                            {
                                @Html.RadioButtonFor(x => x.AuthorizationEnabled, false, new { @class = "required" })
                            }
                            @app.T["disabled"]
                        </label>
                    </div>
                </div>
                <div class="form-group col-sm-12">
                    @Html.LabelFor(x => x.Description, app.T["attribute_description"], new { @class = "col-sm-2 control-label" })
                    <div class="col-sm-10">
                        @Html.TextAreaFor(x => x.Description, new { @class = "form-control", @row = 5 })
                    </div>
                </div>
                <div class="form-group col-sm-12">
                    <label class="col-sm-2 control-label" for="attributetype">@app.T["attribute_typename"]</label>
                    <div class="col-sm-10">
                        <select name="attributetype" id="attributetype" class="form-control required" data-value="@Model.Attribute.AttributeTypeName" disabled="disabled">
                            <option value="">@app.T["select"]</option>
                            <option value="nvarchar">@app.T["text"]</option>
                            <option value="ntext">@app.T["large_text"]</option>
                            <option value="int">@app.T["integer"]</option>
                            <option value="float">@app.T["float"]</option>
                            <option value="money">@app.T["money"]</option>
                            <option value="picklist">@app.T["optionset"]</option>
                            <option value="bit">@app.T["yes_or_no"]</option>
                            <option value="datetime">@app.T["attribute_datetime"]</option>
                            <option value="lookup">@app.T["entity_quote"]</option>
                            <option value="uniqueidentifier">全局唯一码</option>
                            <option value="state">状态</option>
                            <option value="status">状态描述</option>
                            <option value="partylist">多选</option>
                        </select>
                    </div>
                </div>
                <div id="settings">
                    @if (Model.Attribute.TypeIsNvarchar())
                    {
                        <div class="hide" id="nvarcharSetting">
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="nvarchar-format">@app.T["attribute_format"]</label>
                                <div class="col-sm-10">
                                    <select name="textformat" id="nvarchar-format" class="form-control" data-value="@Model.Attribute.DataFormat">
                                        <option value="text">@app.T["unlimited"]</option>
                                        <option value="email">@app.T["email"]</option>
                                        <option value="url">@app.T["link"]</option>
                                        <option value="unlink">@app.T["text"]</option>
                                        <option value="password">@app.T["password"]</option>
                                        <option value="textarea">多行文本</option>
                                        <option value="fileupload">文件上传</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="nvarchar-length">@app.T["attribute_maxlength"]</label>
                                <div class="col-sm-10">
                                    <input name="maxlength" id="nvarchar-length" value="@Model.Attribute.MaxLength.ToString("0")" class="form-control input-sm" data-type="int" data-range="[10,4000]" />
                                </div>
                            </div>
                        </div>
                    }
                    else if (Model.Attribute.TypeIsNText())
                    {
                        <div class="hide" id="ntextSetting">
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="ntext-format">@app.T["attribute_format"]</label>
                                <div class="col-sm-10">
                                    <select name="ntextformat" id="ntext-format" class="form-control" data-value="@Model.Attribute.DataFormat">
                                        <option value="text">@app.T["unlimited"]</option>
                                        <option value="email">@app.T["rich_text"]</option>
                                        <option value="fileupload">文件上传</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    }
                    else if (Model.Attribute.TypeIsInt())
                    {
                        <div class="hide" id="intSetting">
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="int-minvalue">@app.T["attribute_minvalue"]</label>
                                <div class="col-sm-10">
                                    <input name="intminvalue" id="int-minvalue" value="@((int)Model.Attribute.MinValue)" class="form-control input-sm" data-range="[-2147483648,2147483647]" />
                                </div>
                            </div>
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="int-maxvalue">@app.T["attribute_maxvalue"]</label>
                                <div class="col-sm-10"><input name="intmaxvalue" id="int-maxvalue" value="@(Convert.ToInt64(Model.Attribute.MaxValue))" class="form-control input-sm" data-range="[-2147483648,2147483647]" /></div>
                            </div>
                        </div>
                    }
                    else if (Model.Attribute.TypeIsFloat())
                    {
                        <div class="hide" id="floatSetting">
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="float-precision">@app.T["attribute_precision"]</label>
                                <div class="col-sm-10">
                                    <input name="floatprecision" id="float-precision" value="@Model.Attribute.Precision" class="form-control input-sm" data-range="[0,8]" />
                                </div>
                            </div>
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="float-minvalue">@app.T["attribute_minvalue"]</label>
                                <div class="col-sm-10">
                                    <input name="floatminvalue" id="float-minvalue" value="@Math.Round(Model.Attribute.MinValue,2).ToString("f2")" class="form-control input-sm" data-range="[-2147483648,2147483647]" />
                                </div>
                            </div>
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="float-maxvalue">@app.T["attribute_maxvalue"]</label>
                                <div class="col-sm-10">
                                    <input name="floatmaxvalue" id="float-maxvalue" value="@Math.Round(Model.Attribute.MaxValue,2).ToString("f2")" class="form-control input-sm" data-range="[-2147483648,2147483647]" />
                                </div>
                            </div>
                        </div>
                    }
                    else if (Model.Attribute.TypeIsMoney())
                    {
                        <div class="hide" id="moneySetting">
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="money-precision">@app.T["attribute_precision"]</label>
                                <div class="col-sm-10">
                                    <input name="moneyprecision" id="money-precision" value="@Model.Attribute.Precision" class="form-control input-sm" data-range="[0,8]" />
                                </div>
                            </div>
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="money-minvalue">@app.T["attribute_minvalue"]</label>
                                <div class="col-sm-10">
                                    <input name="moneyminvalue" id="money-minvalue" value="@Math.Round(Model.Attribute.MinValue,2).ToString("f2")" class="form-control input-sm" data-range="[-2147483648,2147483647]" />
                                </div>
                            </div>
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="money-maxvalue">@app.T["attribute_maxvalue"]</label>
                                <div class="col-sm-10">
                                    <input name="moneymaxvalue" id="money-maxvalue" value="@Math.Round(Model.Attribute.MaxValue,2).ToString("f2")" class="form-control input-sm" data-range="[-2147483648,2147483647]" />
                                </div>
                            </div>
                        </div>
                    }
                    else if (Model.Attribute.TypeIsPickList() || Model.Attribute.TypeIsStatus())
                    {
                        <div class="hide" id="picklistSetting">
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="optionset-type">@app.T["attribute_format"]</label>
                                <div class="col-sm-10">
                                    <select name="optionsettype" id="optionset-type" class="form-control" data-value="@Model.Attribute.DisplayStyle">
                                        <option value="select">@app.T["drop_down"]</option>
                                        @*<option value="checkbox">@app.T["check"]</option>*@
                                        <option value="radio">@app.T["radiobox"]</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="optionset-picklist">@app.T["attribute_optionset_items"]</label>
                                <div class="col-sm-10">
                                    @if (Model.IsCommonOptionSet)
                                    {
                                        <label class="control-label">
                                            <input type="checkbox" value="true" name="iscommonoptionset" onclick="selectOptionset(this)" @(Model.IsCommonOptionSet ? "checked" : "") @(Model.IsCommonOptionSet ? "disabled" : "") />
                                            @app.T["attribute_select_existing_option"]
                                        </label>
                                        <div id="optionset-commonarea" class="input-group col-sm-12 disabled @(Model.IsCommonOptionSet ? "" : "hide")">
                                            <select name="commonoptionset" id="optionset-common" class="form-control input-sm" data-value="@Model.Attribute.OptionSetId" disabled></select>
                                            <span class="input-group-btn hide">
                                                <button type="button" class="btn btn-default btn-sm" onclick="loadOptionSet()" title="@app.T["refresh"]">
                                                    <span class="glyphicon glyphicon-refresh"></span>
                                                </button>
                                                <button type="button" class="btn btn-primary btn-sm" onclick="Xms.Web.OpenWindow(ORG_SERVERURL+'/customize/optionset/createoptionset?solutionid=@Model.SolutionId')">
                                                    @app.T["new"]
                                                </button>
                                            </span>
                                        </div>
                                    }
                                    else
                                    {
                                        <div id="optionset-privatearea">
                                            <div class="btn-group">
                                                <button type="button" class="btn btn-primary btn-xs" onclick="addOption('optionset-picklist')">
                                                    <span class="glyphicon glyphicon-plus-sign"></span> @app.T["item_add"]
                                                </button>
                                                <button type="button" class="btn btn-default btn-xs" onclick="clearOption('optionset-picklist')">
                                                    <span class="glyphicon glyphicon-trash"></span> @app.T["clear"]
                                                </button>
                                            </div>
                                            <table id="optionset-picklist" class="table">
                                                <thead>
                                                    <tr>
                                                        <th>@app.T["optionset_item_name"]</th>
                                                        <th>@app.T["optionset_item_value"]</th>
                                                        <th>@app.T["optionset_item_defaultselected"]</th>
                                                        <th>@app.T["operation"]</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    @if (Model.Attribute.OptionSet.Items.NotEmpty())
                                                    {
                                                        foreach (var item in Model.Attribute.OptionSet.Items)
                                                        {
                                                            <tr>
                                                                <td>
                                                                    <input onblur="CheckRepeat('optionsetname')" type="text" class="optionsetname" name="optionsetname" maxlength="200" value="@item.Name" />
                                                                    <input type="hidden" name="optionsetdetailid" value="@item.OptionSetDetailId" />
                                                                </td>
                                                                <td><input onblur="CheckRepeat('optionsetvalue')" type="text" class="optionsetvalue" name="optionsetvalue" data-range="[-2147483648,2147483648]" value="@item.Value" /></td>
                                                                <td>
                                                                    <input type="checkbox" name="optionListChecker" onclick="$(this).next().val($(this).prop('checked'))" @(item.IsSelected ? "checked" : "") />
                                                                    <input name="isselectedoption" type="hidden" value="@(item.IsSelected.ToString())" />
                                                                </td>
                                                                <td>
                                                                    <button type="button" class="btn btn-warning btn-xs" onclick="removeOption('optionset-picklist', this)">
                                                                        <span class="glyphicon glyphicon-trash"></span>
                                                                    </button>
                                                                    <button type="button" class="btn btn-info btn-xs" onclick="moveOption('optionset-picklist', this, true)">
                                                                        <span class="glyphicon glyphicon-arrow-up"></span>
                                                                    </button>
                                                                    <button type="button" class="btn btn-info btn-xs" onclick="moveOption('optionset-picklist', this, false)">
                                                                        <span class="glyphicon glyphicon-arrow-down"></span>
                                                                    </button>
                                                                </td>
                                                            </tr>
                                                        }
                                                    }
                                                    else
                                                    {
                                                        <tr>
                                                            <td>
                                                                <input onblur="CheckRepeat('optionsetname')" type="text" class="optionsetname" name="optionsetname" maxlength="200" />
                                                                <input type="hidden" name="optionsetdetailid" value="@Guid.Empty" />
                                                            </td>
                                                            <td><input onblur="CheckRepeat('optionsetvalue')" type="text" class="optionsetvalue" name="optionsetvalue" data-range="[-2147483648,2147483648]" /></td>
                                                            <td>
                                                                <input type="checkbox" name="optionListChecker" onclick="$(this).next().val($(this).prop('checked'))" />
                                                                <input name="isselectedoption" type="hidden" value="false" />
                                                            </td>
                                                            <td>
                                                                <button type="button" class="btn btn-warning btn-xs" onclick="removeOption('optionset-picklist', this)">
                                                                    <span class="glyphicon glyphicon-trash"></span>
                                                                </button>
                                                                <button type="button" class="btn btn-info btn-xs" onclick="moveOption('optionset-picklist', this, true)">
                                                                    <span class="glyphicon glyphicon-arrow-up"></span>
                                                                </button>
                                                                <button type="button" class="btn btn-info btn-xs" onclick="moveOption('optionset-picklist', this, false)">
                                                                    <span class="glyphicon glyphicon-arrow-down"></span>
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    }
                                                </tbody>
                                            </table>
                                        </div>
                                    }
                                </div>
                            </div>
                        </div>
                    }
                    else if (Model.Attribute.TypeIsBit() || Model.Attribute.TypeIsState())
                    {
                        var trueObj = Model.Attribute.PickLists.Find(n => n.Value == 1);
                        var falseObj = Model.Attribute.PickLists.Find(n => n.Value == 0);
                        var truechecked = "";
                        var falsechecked = "";
                        if (trueObj.Value == 1)
                        {
                            truechecked = "checked='true'";
                        }
                        else if (falseObj.Value == 1)
                        {
                            falsechecked = "checked='true'";
                        }
                        <div class="form-group col-sm-12" id="bitSetting">
                            <label class="col-sm-2 control-label" for="bit-option">@app.T["attribute_optionset_items"]</label>
                            <div class="col-sm-10">
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th>@app.T["optionset_item_name"]</th>
                                            <th>@app.T["optionset_item_defaultselected"]</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td>
                                                @app.T["true"]：<input type="text" name="bitoptionname" value="@trueObj.Name" maxlength="200" />
                                                <input type="hidden" name="bitdetailid" value="@trueObj.StringMapId" />
                                            </td>
                                            <td>
                                                <input type="checkbox" name="bitisdefault" @truechecked value="true" />
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                                                @app.T["false"]：<input type="text" name="bitoptionname" value="@falseObj.Name" maxlength="200" />
                                                <input type="hidden" name="bitdetailid" value="@falseObj.StringMapId" />
                                            </td>
                                            <td>
                                                <input type="checkbox" name="bitisdefault" @falsechecked value="false" />
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                    }
                    else if (Model.Attribute.TypeIsDateTime())
                    {
                        <div class="form-group col-sm-12" id="datetimeSetting">
                            <label class="col-sm-2 control-label" for="datetime-format">@app.T["attribute_format"]</label>
                            <div class="col-sm-10">
                                <select name="datetimeformat" id="datetime-format" class="form-control" data-value="@Model.Attribute.DataFormat">
                                    <option value="yyyy/MM/dd">@app.T["attribute_dateformat_date"]</option>
                                    <option value="yyyy/MM/dd hh:mm:ss">@app.T["attribute_dateformat_datetime"]</option>
                                </select>
                            </div>
                        </div>
                    }
                    else if (Model.Attribute.TypeIsLookUp())
                    {
                        <div class="hide" id="lookupSetting">
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="lookup-entity">@app.T["entity"]</label>
                                <div class="col-sm-10">
                                    <select name="lookupentity" id="lookup-entity" class="form-control" data-value="@Model.Attribute.ReferencedEntityId" disabled></select>
                                </div>
                            </div>
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="nvarchar-format">@app.T["attribute_format"]</label>
                                <div class="col-sm-10">
                                    <select name="LookupType" id="lookup-type" class="form-control" data-value="@Model.Attribute.DisplayStyle">
                                        <option value="link">@app.T["link"]</option>
                                        <option value="unlink">@app.T["text"]</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    }
                    else if (Model.Attribute.TypeIsPartyList())
                    {
                        <div class="hide" id="partylistSetting">
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="partylist-format">@app.T["attribute_format"]</label>
                                <div class="col-sm-10">
                                    <select name="partylistformat" id="partylist-format" class="form-control" data-value="@Model.Attribute.DataFormat">
                                        <option value="checkbox">复选框</option>
                                        <option value="lookup">查找框</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    }
                </div>
                <fieldset class="col-sm-12 hide" id="valueSetting">
                    <legend>值设置</legend>
                    <div class="form-group col-sm-12">
                        <label class="col-sm-2 control-label" for="valuetype">来源</label>
                        <div class="col-sm-10">
                            <select class="form-control" name="valuetype" id="valuetype" data-value="@Model.ValueType">
                                <option value="0">无</option>
                                <option value="1">默认值</option>
                                <option value="2">计算公式</option>
                                <option value="3">累计汇总</option>
                            </select>
                        </div>
                    </div>
                    <div id="valueSection">
                        <div class="hide" id="defaultSection">
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" id="defaultvalue">输入值</label>
                                <div class="col-sm-10">
                                    <textarea class="form-control" name="defaultvalue">@Model.DefaultValue</textarea>
                                </div>
                            </div>
                        </div>
                        <div class="hide" id="summarySection">
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="int-minvalue">汇总对象</label>
                                <div class="col-sm-10">
                                    <select class="form-control" name="summaryentityid" id="summaryentityid" data-value="@Model.AaExp.RelationshipName"></select>
                                </div>
                            </div>
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="summarytype">运算类型</label>
                                <div class="col-sm-4">
                                    <select class="form-control" name="summarytype" id="summarytype" data-value="@Model.AaExp.Aggregate">
                                        <option value="count">计数</option>
                                        <option value="sum">合计</option>
                                        <option value="max">最大值</option>
                                        <option value="min">最小值</option>
                                    </select>
                                </div>
                                <label class="col-sm-2 control-label" for="summaryfield">运算字段</label>
                                <div class="col-sm-4">
                                    <select class="form-control" name="summaryfield" id="summaryfield" data-value="@Model.AaExp.Field"></select>
                                </div>
                            </div>
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label" for="summaryfiltertype">过滤条件</label>
                                <div class="col-sm-10">
                                    <label class="checkbox-inline"><input type="radio" name="summaryfiltertype" id="summaryfiltertype" value="1" checked />包含所有记录</label>
                                    <label class="checkbox-inline"><input type="radio" name="summaryfiltertype" id="summaryfiltertype" value="2" />指定条件记录</label>
                                </div>
                                <div class="col-sm-10 col-sm-offset-2 hide" id="filterSection">
                                    <table class="table">
                                        <thead><tr><th>字段</th><th>运算符</th><th>值</th><th class="col-sm-4"></th></tr></thead>
                                        <tbody>
                                            <tr class="condition-clone-default" style="display:none;">
                                                <td>
                                                    <select class="form-control filter-filed-name"></select>
                                                </td>
                                                <td>
                                                    <select class="form-control filter-filed-Operator"></select>
                                                </td>
                                                <td>
                                                    <input class="form-control filter-filed-value" name="value" type="text" />
                                                </td>
                                                <td>
                                                    <button type="button" class="btn btn-xs btn-warning" onclick="removeCondition(this)">
                                                        <span class="glyphicon glyphicon-minus-sign"></span>
                                                    </button>
                                                </td>
                                            </tr>
                                            <tr class="condition-item">
                                                <td>
                                                    <select class="form-control filter-filed-name"></select>
                                                </td>
                                                <td>
                                                    <select class="form-control filter-filed-Operator"></select>
                                                </td>
                                                <td>
                                                    <input class="form-control filter-filed-value" name="value" type="text" />
                                                </td>
                                                <td>
                                                    <button type="button" class="btn btn-xs btn-info" onclick="addCondition(this)">
                                                        <span class="glyphicon glyphicon-plus-sign"></span>
                                                    </button>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <div class="hide" id="formulaSection">
                            <div class="form-group col-sm-12">
                                <label class="col-sm-2 control-label">公式</label>
                                <div class="col-sm-10">
                                    <textarea class="form-control" id="formula">@Model.FormulaExpression</textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                </fieldset>
                <div class="form-group col-sm-12 text-center" id="form-buttons">
                    <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-saved"></span> @app.T["save"]</button>
                    <button type="reset" class="btn btn-default"><span class="glyphicon glyphicon-refresh"></span> @app.T["reset"]</button>
                </div>
            </form>
        </div>
    </div>
</div>
@section Scripts {
    <script src="/content/js/fetch.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/filterdialog.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery.form.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery-validate/jquery.validate.min.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery-validate/localization/messages_zh.min.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/knockout-2.2.0.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/xms.metadata.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script>
        var isPkField = @(Model.Attribute.AttributeTypeName.IsCaseInsensitiveEqual("primarykey") ? "true":"false")
        $(function () {
            if (isPkField) {
                $("#editform input[type!=hidden]").prop("disabled", "disabled");
                $("#editform textarea").prop("disabled", "disabled");
                $("#editform select").prop("disabled", "disabled");
                $("#editform button").prop("disabled", "disabled");
                $('#attributetype').prepend('<option>' + LOC_ATTRIBUTETYPE_PRIMARYKEY + '</option>');
                $('#LocalizedName').removeProp('disabled');
                $('#form-buttons button').removeProp('disabled');
            }
            //表单验证
            Xms.Web.Form($("#editform"), null, null, function () {
                var nameCheck = CheckRepeat('optionsetname');
                var valueCheck = CheckRepeat('optionsetvalue');
                if (!nameCheck || !valueCheck) {
                    return false;
                }
            });
            //字段类型
            $('#attributetype').bind("change", function () {
                $('#settings').children().addClass('hide');
                var type = $(this).val();
                if (type == 'state') type = 'bit';
                if (type == 'status') type = 'picklist';
                $('#' + type + 'Setting').removeClass('hide');
                if (type == 'lookup') {
                    //绑定引用实体
                    loadEntities();
                }
            });
            $('#summaryentityid').on('change', null, function (e) {
                LoadSummaryAttributes();
            });
            Xms.Web.SelectedValue($('#summaryentityid'), $('#summaryentityid').attr('data-value'));
            $('#valuetype').on('change', null, function (e) {
                var vt = $(this).val();
                //var at = Xms.Web.SelectedValue($('#attributetype'));
                $('#valueSection').children().addClass('hide');
                if (vt == 1) {
                    $('#defaultSection').removeClass('hide');
                }
                else if (vt == 2) {
                    $('#formulaSection').removeClass('hide');
                }
                else if (vt == 3) {
                    LoadRelatedEntities();
                    $('#summarySection').removeClass('hide');
                } else {
                    valueSetJson()
                }
            });
            Xms.Web.SelectedValue($('#valuetype'), $('#valuetype').attr('data-value'));
            $('input[name=summaryfiltertype]').on('change', null, function (e) {
                var t = $(this).val();
                if (t == 2) {
                    $('#filterSection').removeClass('hide');
                } else {
                    $('#filterSection').addClass('hide');
                }
            });
            Xms.Web.SelectedValue($('#summarytype'), $('#summarytype').attr('data-value'));
            //选项集
            Xms.Web.SingleCheckbox('#optionset-picklist', 'input[type=checkbox]', 'single', function (context) {
                console.log($(this))
                var hideIn = $(this).siblings("input[name='isselectedoption']");
                $("input[name='isselectedoption']").val('false');
                hideIn.val(true);
            }, true);
            $('#optionset-type').bind("change", function () {
                var t = $(this).find('option:selected').val();
                if (t == 'checkbox') {
                    Xms.Web.SingleCheckbox('#optionset-picklist', 'input[type=checkbox]', 'multi');
                    $("input[type=checkbox]", '#optionset-picklist').unbind("click").bind("click", function (context) {
                        var hideIn = $(this).siblings("input[name='isselectedoption']");
                        hideIn.val($(this).prop("checked"));
                    });
                }
                else {
                    Xms.Web.SingleCheckbox('#optionset-picklist', 'input[type=checkbox]', 'single', function (context) {
                        var hideIn = $(this).siblings("input[name='isselectedoption']");
                        $("input[name='isselectedoption']").val('false');
                        hideIn.val(true);
                    }, true);
                }
            });
            //复选框设置为单选
            Xms.Web.SingleCheckbox('#bitSetting', 'input[type=checkbox]', 'single', function (context) {
                console.log($(this))
                var hideIn = $(this);//.siblings("input[name='isselectedoption'],input[name='bitisdefault']");
                $("input[type=checkbox]", '#bitSetting').val(false);
                hideIn.val(true);
            }, true);
            //下拉选择框绑定值
            $('select[data-value]').each(function (i, n) {
                var self = $(n);
                Xms.Web.SelectedValue(self, self.attr('data-value'));
                self.trigger('change');
            });
            var iscommonoptionset = $('input[name=iscommonoptionset]').prop('checked');
            if (iscommonoptionset == true) {
                loadOptionSet();
            }

            $('button[type="submit"]').off('click').on('click', function (e) {
                e.preventDefault();
                valueSetJson();
                $('form:first').submit();
            });

            // loadFilterData(
            //      function () {
            //         var timer = setInterval(function () {
            //             if ($('#summaryfield').children('option').length > 0) {
            renderFilterDom();
            //               clearInterval(timer)
            //            }
            //        }, 10);

            //     });

            //如果有已存在的值计算内容的时候

        });

        //加载已存在的值计算内容
        function renderFilterDom() {
            var $summaryexpression = $('#SummaryExpression');
            if ($summaryexpression.val() == "") {
                return false;
            }
            console.log($summaryexpression.val())
            var expressionData = JSON.parse($summaryexpression.val());
            //设置来源
            $('#valuetype').find('>option[value="3"]').prop('selected', true);
            //设置汇总对象
            if (expressionData.lk_opportunityproduct_opportunityid != "") {
                $('#summaryentityid').find('>option[data-relationshipname="' + expressionData.lk_opportunityproduct_opportunityid + '"]').prop('selected', true);
            }
            //设置运算类型
            if (expressionData.aggregate != "") {
                $('#summarytype').find('>option[value="' + expressionData.aggregate + '"]').prop('selected', true);
            }
            //设置运算字段
            if (expressionData.field != "") {
                $('#summaryfield').find('>option[data-name="' + expressionData.field + '"]').prop('selected', true);
            }
            //设置过滤条件
            if (expressionData.filter && expressionData.filter != "") {
                $('input[name="summaryfiltertype"][value="2"]').prop('checked', true);
                $('#filterSection').removeClass('hide');
                var filterArr = expressionData.filter.Conditions;

                /*加载字段*/
                var entityid = $('#EntityId').val();
                var filters = Xms.Fetch.FilterExpression();
                filters.Conditions = expressionData.filter.Conditions;
                var postData = {
                    entityid: entityid,
                    filter: filters
                }
                Xms.Web.Post('/filter/simplefiltersection', postData, false, function (res) {

                    $('#filterSection').html(res);
                })
            }
        }
        //选项集-增加选项
        function addOption(id, row) {
            var $target = $("#" + id);
            var newRow = row ? row.clone() : $target.find('tr:last').clone();
            newRow.find('input[type=text]').val('');
            newRow.find('input[type=hidden]').val('');
            newRow.find('input[name=optionsetdetailid]').val(Xms.Utility.Guid.EmptyGuid.ToString());
            newRow.find('input[type=checkbox]').prop('checked', false);
            newRow.find("input[name='isselectedoption']").val('false');
            //if(row) $target.find('tbody').empty();
            $target.find('tbody').append(newRow);
        }
        //选项集-删除选项
        function removeOption(id, row) {
            var $target = $("#" + id);
            if ($(row).parents('tr').siblings().length > 0) {
                $(row).parents('tr').remove();
            }
            else {
                var newRow = $(row).parents('tr');
                //addOption(id, newRow);
                newRow.find('input[type=text]').val('');
                newRow.find('input[type=checkbox]').prop('checked', false);
            }
        }
        //选项集-清空选项
        function clearOption(id) {
            var $target = $("#" + id);
            $target.find('tbody').find('tr:gt(0)').remove();

            var newRow = $target.find('tbody').find('tr:last');
            newRow.find('input[type=text]').val('');
            newRow.find('input[type=checkbox]').prop('checked', false);
            //addOption(id);
        }
        //选项集-排序选项
        function moveOption(id, row, isup) {
            var $target = $("#" + id);
            var $this = $(row).parents('tr');
            if (isup == true && $this.prev().length > 0) {
                $this.insertBefore($this.prev());
            }
            else if (isup == false && $this.next().length > 0) {
                $this.insertAfter($this.next());
            }
        }
        //公共选项集or私有
        function selectOptionset(o) {
            var $this = $(o);
            if ($this.prop('checked') == true) {
                $('#optionset-commonarea').removeClass('hide');
                $('#optionset-privatearea').addClass('hide');
                loadOptionSet();
            }
            else {
                $('#optionset-privatearea').removeClass('hide');
                $('#optionset-commonarea').addClass('hide');
            }
        }
        //加载公共选项集
        function loadOptionSet() {
            var optionsetSelect = $('#optionset-common');
            optionsetSelect.empty();
            Xms.Web.GetJson("/api/schema/optionset", {ispublic:true, getall:true}, function (data) {
                console.log(data);
                if (!data || !data.content || data.content.length == 0) return;
                $(data.content).each(function (i, n) {
                    optionsetSelect.append("<option value=\"" + n.optionsetid + "\">" + n.name + "</option>");
                });
                Xms.Web.SelectedValue(optionsetSelect, optionsetSelect.attr('data-value'));
            });
        }
        //加载引用实体
        function loadEntities() {
            var entitySelect = $('#lookup-entity');
            entitySelect.empty();
            Xms.Schema.GetEntityById(entitySelect.attr('data-value'), function (data) {
                entitySelect.append("<option value=\"" + data.entityid + "\">" + data.localizedname + "</option>");
            });
        }
        //检查是否有重复的值
        function CheckRepeat(classname) {
            var check = true;
            $('.' + classname).each(function (i, n) {
                var nVal = $(n).val();
                var ncheck = true;
                if (nVal == '') {
                    return true;
                }
                $('.' + classname).each(function (ii, nn) {
                    var nnVal = $(nn).val();
                    if (nnVal == '') {
                        return true;
                    }
                    if (nVal == nnVal && i != ii) {
                        if ($(n).next('label[name="repeatTip"]').length == 0) {
                            $('<label name="repeatTip">' + LOC_ATTRIBUTE_OPTION_DUPLICATED + '</label>').insertAfter($(n));
                        }
                        ncheck = false;
                        check = false;
                        return false;
                    }
                });
                if (ncheck == true) {
                    $(n).next('label[name="repeatTip"]').remove();
                }
            });
            return check;
        }
        //加载汇总来源实体
        function LoadRelatedEntities() {
            var _target = $('#summaryentityid');
            var entityid = $('#EntityId').val();
            Xms.Web.GetJson('/api/schema/relationship/GetReferenced/' + entityid, null, function (data) {
                if (!data || data.content.length == 0) return;
                //_target.append('<option value="">--请选择--</option>');
                var html = [];

                $(data.content).each(function (i, n) {
                    html.push('<option data-relationshipname="' + n.name + '" data-referencingentityname="' + n.referencingentityname + '" value="' + n.referencingentityid + '">' + n.referencingentitylocalizedname + '(' + n.referencedentitylocalizedname + ')' + '</option>')

                });
                _target.html(html.join(''));
                _target.trigger('change');
            }, null, false);
        }
        //加载汇总来源字段
        function LoadSummaryAttributes() {
            var entityid = Xms.Web.SelectedValue($('#summaryentityid'));
            if (!entityid) return;
            var _target = $('#summaryfield');
            _target.empty();
            var filter = { 'GetAll': true, "entityid": entityid, "attributetypename": ['int', 'money', 'float'] };
            Xms.Schema.GetAttributes(filter, function (data) {
                if (!data || data.length == 0) return;
                var html = [];
                $(data).each(function (i, n) {
                    html.push('<option value="' + n.attributeid + '" data-name="' + n.name + '" data-attributename="' + n.attributetypename + '">' + n.localizedname + '</option>')

                });
                _target.html(html.join(''));
            }, null, false, 'post');
        }

        var se = { "aggregate": "sum", "entityname": "opportunityproduct", "field": "amount", "filter": null, "relationshipname": "lk_opportunityproduct_opportunityid" };
        //设置值得JSON数据
        function valueSetJson() {
            var $value = $('#SummaryExpression');
            var $valuetype = $('#valuetype');
            if ($valuetype.val() == 0) {
                $value.val('');
            } else {
                se.aggregate = $('#summarytype').val();
                se.entityname = $('#summaryentityid option:selected').attr('data-referencingentityname');
                se.field = $('#summaryfield option:selected').attr('data-name');
                if ($('input[name="summaryfiltertype"]:checked').val() == 1) {
                    se.filter = null;
                } else {
                    setFiltersData();
                    if ($('#filterConditions').val() != "") {
                        se.filter = JSON.parse(decodeURIComponent($('#filterConditions').val()));
                    }
                }
                se.relationshipname = $('#summaryentityid option:selected').attr('data-relationshipname');
                console.log('过滤条件数据', se);
                $value.val('').val(JSON.stringify(se));
            }
        }
        function setFiltersData() {
            var filterConditions = $('#filterConditions');
            var $conditions = $('.condition-item');
            var filters = Xms.Fetch.FilterExpression();
            $conditions.each(function () {
                var item = Xms.Fetch.ConditionExpression();
                item.AttributeName = $(this).find('.filter-filed-name').val();
                item.Operator = $(this).find('.filter-filed-Operator').val();
                item.Values.push($(this).find('input[name="value"]').val());
                if ($(this).find('input[name="value"]').val() != "") {
                    filters.Conditions.push(item);
                }
            });

            filterConditions.val(encodeURIComponent(JSON.stringify(filters)));
        }
    </script>
}